#!/bin/bash
source ./check.config
pkglist=$1

function check_input_and_config(){
	# check pkglist
	if [ ! -f ${pkglist} ];then
		echo "package list file ${pkglist} does not exist!"
		exit 1
	fi
	# check yum repo file
	if [ ! -f "${yum_repo}" ]; then
		echo "yum repo file doesn't exist!"
		exit 1
	fi
	echo "Downloading docker image, please wait..."
	wget ${docker_url}
	if [ $? -ne 0 ];then
	        echo "downloading docker image source failed!"
	        exit 1
	fi
	docker_image_source=$(echo ${docker_url} | awk -F "/" '{print $NF}')
	docker_image_name=$(docker load < ${docker_image_source} | sed 's/Loaded image: //g')
}

function create_env(){
	echo "Creating docker env, please wait..."
	# clean previous docker env
	docker stop test_build &>/dev/null
	docker rm test_build &>/dev/null
	# create docker and share result folder 
	docker run -itd -v ${init_path}/build_result:/root/build_result --net=host --name=test_build --privileged=true ${docker_image_name} /bin/bash &>/dev/null
	if [ $? -ne 0 ];then
		echo "creating docker failed!"
		exit 1
	fi
	# copy files into docker, will check files exist or not in script build_indocker.sh
	docker cp ${yum_repo} test_build:/root/
	docker cp build_indocker.sh test_build:/root/
	docker exec -it test_build bash -c 'echo "export TMOUT=0" >> /etc/bashrc && source /etc/bashrc 2>/dev/null && exit'
	docker restart test_build &>/dev/null
	echo "Create docker env completed !!!"
}

function check_build(){
	docker exec -it test_build /bin/bash -c "cd /root/ && bash build_indocker.sh -p $1"
	if [ $? -eq 0 ]; then
		docker stop test_build &>/dev/null
		docker rm test_build &>/dev/null
		echo "Clear docker env complete !!!"
		echo "Self-build for $1 is completed, you can see log file in directory: ${init_path}/build_result, please backup build_result dir !!!"
		rm ${docker_image_source} -f
	else
		docker stop test_build &>/dev/null
		docker rm test_build &>/dev/null
		echo "Clear docker env complete !!!"
		echo "Self-build for $1 failed, you can see log file in directory: ${init_path}/build_result, please backup build_result dir !!!"
		rm ${docker_image_source} -f
	fi
}

function main(){
	rm -rf build_result
	mkdir build_result
	init_path=$(pwd)
	for pkg in $(cat $pkglist)
	do
		echo "Start processing package ${pkg}"
		create_env
		check_build ${pkg}
	done
}

echo "=============================================Begin============================================="
check_input_and_config $@
main
echo "==============================================End=============================================="
